package com.shopcart.service.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.dialet.PaginationSupport;
import com.demo.util.DateUtil;
import com.demo.util.SqlUtils;
import com.demo.util.StringUtil;
import com.shopcart.domain.QuickShopping;
import com.shopcart.repository.QuickShoppingRepository;
import com.shopcart.service.QuickShoppingService;
import com.vsd.daoEx.model.QuickShoppingEx;
import com.vsd.service.CodeService;
import com.zy.order.proto.MSOrder.MMiniGoods;
import com.zy.order.proto.MSOrder.MMiniGoodsList;

@Service
@Transactional
public class QuickShoppingServiceImpl implements QuickShoppingService {

	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory
			.getLogger(QuickShoppingServiceImpl.class);
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Autowired
	private QuickShoppingRepository quickShoppingRepository;
	@Autowired
	private CodeService codeService;
	
	@Override
	public List<String> selectTodayPriod(String areaCode) {
		String sql = "select extract(hour FROM s.begin_time) as period	from s_quick_shopping s "
				+ "LEFT JOIN s_store_goods g on g.id = s.gid	left JOIN s_store ss on ss.id = g.store_id"
				+ "	where s.state = 3 and g.type=2 and  g.is_del = 0 and g.is_online = 1 and (ss.area_code like '"+areaCode+"%' or ss.area_code = '0')	"
				+ "and s.begin_time BETWEEN date_add(now(), interval -1 hour) and date_format(CONCAT(curdate(),' 23:59:59'),  '%Y-%m-%d %H:%i:%s')	"
				+ "GROUP BY extract(hour FROM s.begin_time) having period > extract(HOUR FROM date_add(now(), INTERVAL - 1 HOUR))	ORDER BY period";
		List<String> ret = new ArrayList<>();
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> map : maps) {
			ret.add(StringUtil.obj2String(map.get("period")));
		}
		
		return ret;
	}
	
	@Override
	public List<String> selectGoodsImg(String priod,String areaCode){
		String sql = "select g.img	from s_quick_shopping s 	LEFT JOIN s_store_goods g on g.id = s.gid"
				+ "	left join s_store ss on ss.id = g.store_id	where g.type=2 and g.is_del = 0 and g.is_online = 1 and s.state = 3"
				+ "	 and (ss.area_code ='"+areaCode+"' or ss.area_code = '0')	and s.begin_time BETWEEN "
				+ "date_format(CONCAT(curdate(),' 00:00:00'),  '%Y-%m-%d %H:%i:%s') and "
				+ "date_format(CONCAT(curdate(),' 23:59:59'),  '%Y-%m-%d %H:%i:%s') and extract(hour FROM s.begin_time) "
				+ "= '"+priod+"' ORDER BY g.sort desc,g.name";
		List<String> ret = new ArrayList<>();
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> map : maps) {
			ret.add(StringUtil.obj2String(map.get("img")));
		}
		return ret;
	}
	
	@Override
	public MMiniGoodsList.Builder selectPeriodGoods(String priod,String areaCode){
		MMiniGoodsList.Builder ret = MMiniGoodsList.newBuilder();
		String sql = "select s.*,g.name,g.img,g.old_price	from s_quick_shopping s 	LEFT JOIN s_store_goods g on g.id = s.gid"
				+ "	left join s_store ss on ss.id = g.store_id	where g.type=2 and g.is_del = 0 and g.is_online = 1 and s.state = 3"
				+ "	 and (ss.area_code like '"+areaCode+"%' or ss.area_code = '0')	and s.begin_time BETWEEN "
				+ "date_format(CONCAT(curdate(),' 00:00:00'),  '%Y-%m-%d %H:%i:%s') and "
				+ "date_format(CONCAT(curdate(),' 23:59:59'),  '%Y-%m-%d %H:%i:%s') and extract(hour FROM s.begin_time) "
				+ "= '"+priod+"' ORDER BY g.sort desc,g.name";
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> map : maps) {
			MMiniGoods.Builder g = MMiniGoods.newBuilder();
			g.setId(StringUtil.obj2String(map.get("gid")));
			g.setLogo(StringUtil.obj2String(map.get("img")));
			g.setPrice(StringUtil.obj2String(map.get("price")));
			g.setTotal(map.get("total")==null?0:new Integer(map.get("total").toString()));
			g.setAllCnt(map.get("all_cnt")==null?0:new Integer(map.get("all_cnt").toString()));
			g.setTitle(StringUtil.obj2String(map.get("name")));
			g.setOldPrice(StringUtil.obj2String(map.get("old_price")));
			ret.addList(g);
		}
		
		return ret;
	}

	@Override
	public void save(QuickShopping s) {
		// TODO Auto-generated method stub
		quickShoppingRepository.save(s);
	}

	@Override
	public List<QuickShoppingEx> selectExList(String areaCode) {
		// TODO Auto-generated method stub
		String sql =" select qs.*,g.name as goodsName,g.img,g.imgs,s.`name` as storeName from  s_quick_shopping qs "
				+ "left join s_store_goods g on qs.gid = g.id left join s_store s on s.id =g.store_id "
				+ "where 1=1 ";
		if(StringUtils.isNotBlank(areaCode)){
			sql+=" and s.area_code like '"+areaCode+"%'";
		}
		sql+=" order by qs.create_time desc";
		
		sql = PaginationSupport.initPage(sql, jdbcTemplate);
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		List<QuickShoppingEx> ret = new ArrayList<>();
		for (Map<String, Object> map : maps) {
			QuickShoppingEx ex = new QuickShoppingEx();
			SqlUtils.transMap2Bean2(map, ex);
			ret.add(ex);
		}
		return ret;
	}

	@Override
	public void delById(String id) {
		// TODO Auto-generated method stub
		quickShoppingRepository.delete(id);
	}

	@Override
	public int updateByPrimaryKey(QuickShopping s) {
		// TODO Auto-generated method stub
		try {
			String sql = SqlUtils.update(s, true, " where gid = '"+s.getGid()+"'");
			return jdbcTemplate.update(sql);
		} catch (Exception e) {
			return 0;
		}
		
	}

	@Override
	public List<QuickShoppingEx> selectByStore(String storeId) {
		// TODO Auto-generated method stub
		String sql =" select qs.*,g.name as goodsName,g.img,g.imgs,s.`name` as storeName from  s_quick_shopping qs "
				+ "left join s_store_goods g on qs.gid = g.id left join s_store s on s.id =g.store_id "
				+ "where g.store_id = '"+storeId+"' order by qs.create_time desc";
		 
		sql = PaginationSupport.initPage(sql, jdbcTemplate);
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		List<QuickShoppingEx> ret = new ArrayList<>();
		for (Map<String, Object> map : maps) {
			QuickShoppingEx ex = new QuickShoppingEx();
			SqlUtils.transMap2Bean2(map, ex);
			ret.add(ex);
		}
		return ret;
	}

	@Override
	public QuickShopping findById(String id) {
		// TODO Auto-generated method stub
		return quickShoppingRepository.findOne(id);
	}

	@Override
	public void updateGoodsModeAndOrder() {
		// TODO Auto-generated method stub
		//将抢购商品置为抢购状态
		String sql = "update s_store_goods sg set sg.mode = 2 where "
				+ " sg.mode = 1 and DATE_FORMAT((select qs.begin_time from (select * from s_store_goods where 1) sg1 "
				+ "left join s_quick_shopping qs on sg1.id = qs.gid where sg1.id = sg.id),'%Y%m%d%H')=DATE_FORMAT(SYSDATE(),'%Y%m%d%H')";
		jdbcTemplate.update(sql);
		//将过期抢购置为正常状态
		Integer minute = codeService.getQuickTime();
		Date end = DateUtil.addMinute(new Date(), 0-minute);
		
		sql="update s_store_goods sg set sg.mode = 1 "
				+ "where sg.mode=2 and  DATE_FORMAT((select qs.begin_time from (select * from s_store_goods where 1)"
				+ " sg1 left join s_quick_shopping qs on sg1.id = qs.gid where sg1.id = sg.id),'%Y-%m-%d %H:%i') <= '"+DateUtil.dateToStr(end, "yyyy-MM-dd HH:mm")+"'";
		jdbcTemplate.update(sql);
		
		//过期未付款订单取消
		sql="update s_order set state = 0 where pay_deadline < SYSDATE() and state=1";
		jdbcTemplate.update(sql);
		
	}
	
	@Override
	public void updateGoodsMode2() {
		// TODO Auto-generated method stub
		//将抢购商品置为抢购状态
		Integer minute = codeService.getQuickTime();
		Date end = DateUtil.addMinute(new Date(), 0-minute);
		
		String sql="update s_store_goods sg set sg.mode = 1 "
				+ "where sg.mode=2 and  DATE_FORMAT((select qs.begin_time from (select * from s_store_goods where 1)"
				+ " sg1 left join s_quick_shopping qs on sg1.id = qs.gid where sg1.id = sg.id),'%Y-%m-%d %H:%i') <= '"+DateUtil.dateToStr(end, "yyyy-MM-dd HH:mm")+"'";
		jdbcTemplate.update(sql);
		
	}
	
	@Override
	public void updateOrder() {
		// TODO Auto-generated method stub
		//过期未付款订单取消
		String sql="update s_order set state = 0 where pay_deadline < SYSDATE() and state=1";
		jdbcTemplate.update(sql);
		
	}

}
